package com.rgp.servicemap.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.common.UrlConstants;
import com.rgp.internalcommon.dto.DicDistrict;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.utils.JointUrlUtils;
import com.rgp.servicemap.event.BatchInsertionEvent;
import com.rgp.servicemap.mapper.DicDistrictMapper;
import com.rgp.servicemap.service.DicDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-15 17:14
 */
@Service
public class DicDistrictServiceImpl implements DicDistrictService {

    public static final Integer SAVEBATCH_DICDISTRICT = 1000;
    List<DicDistrict> dicDistrictList = new ArrayList<>(SAVEBATCH_DICDISTRICT);

    public static Map<String,Integer> DIC_DISTRICT_MAP;

    static {
        DIC_DISTRICT_MAP = new HashMap<>(5);
        DIC_DISTRICT_MAP.put("country",0);
        DIC_DISTRICT_MAP.put("province",1);
        DIC_DISTRICT_MAP.put("city",2);
        DIC_DISTRICT_MAP.put("district",3);
        DIC_DISTRICT_MAP.put("street",3);
    }

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${amap.key}")
    private String secretKey;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DicDistrictMapper dicDistrictMapper;

    @Override
    public ResponseResult loadDicDistrict(String keywords,String subdistrict,String extensions) {

        //1.地区字典url的拼接
        Map<String, String> map = new HashMap<>();
        map.put("keywords",keywords);
        map.put("subdistrict",subdistrict);
        map.put("extensions",extensions);
        map.put("key", secretKey);
        String url = JointUrlUtils.combineUrlAndParameters(UrlConstants.DIC_DISTRICT_URL, map);

        //2.解析结果【【国家0、省1、市2、县3】解析一个插入一个。优化：采用观察者模式，解析100个再批量插入】
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        String status = (String) jsonObject.get("status");
        if (status.equals("0")){
            return ResponseResult.fail(CommonStatusEnum.DIC_DISTRICT_ERROR);
        }
        JSONArray countriesArray = jsonObject.getJSONArray("districts");
        //国家
        JSONObject countryObject = (JSONObject)countriesArray.get(0);
        String countryAdCode = (String)countryObject.get("adcode");
        String countryName = (String)countryObject.get("name");
        String countryLevelName = (String)countryObject.get("level");
        Integer countryLevel = DIC_DISTRICT_MAP.get(countryLevelName);
        String countryAddressCodeParent = "0";
        DicDistrict countryDicDistrict= new DicDistrict();
        countryDicDistrict.setAddressCode(countryAdCode);
        countryDicDistrict.setAddressName(countryName);
        countryDicDistrict.setLevel(countryLevel);
        countryDicDistrict.setParentAddressCode(countryAddressCodeParent);
//        dicDistrictMapper.insert(countryDicDistrict);
        dicDistrictList.add(countryDicDistrict);

        //省份
        String provinceAdCode = null;
        String provinceName = null;
        String provinceLevelName = null;
        Integer provinceLevel = null;
        String provinceAddressCodeParent = countryAdCode;
        JSONObject provinceObject = null;
        //地级市
        String cityAddressCodeParent = null;
        String cityAdCode = null;
        String cityName = null;
        String cityLevelName = null;
        Integer cityLevel = null;
        JSONObject cityObject = null;
        //县城
        String districtAddressCodeParent = null;
        String districtAdCode = null;
        String districtName = null;
        String districtLevelName = null;
        Integer districtLevel = null;
        JSONObject district = null;

        JSONArray provinceDistrictses = countryObject.getJSONArray("districts");
        if (provinceDistrictses.size() > 0){
            for (int p = 0;p < provinceDistrictses.size();p++){
                //解析省份
                provinceObject = (JSONObject)provinceDistrictses.get(p);
                provinceAdCode = (String)provinceObject.get("adcode");
                provinceName = (String)provinceObject.get("name");
                provinceLevelName = (String)provinceObject.get("level");
                provinceLevel = DIC_DISTRICT_MAP.get(provinceLevelName);
                //插入省份节点
                DicDistrict provinceDicDistrict = new DicDistrict();
                provinceDicDistrict.setAddressCode(provinceAdCode);
                provinceDicDistrict.setAddressName(provinceName);
                provinceDicDistrict.setParentAddressCode(provinceAddressCodeParent);
                provinceDicDistrict.setLevel(provinceLevel);
//                dicDistrictMapper.insert(provinceDicDistrict);
                dicDistrictList.add(provinceDicDistrict);
                if (dicDistrictList.size() == SAVEBATCH_DICDISTRICT){
                    applicationContext.publishEvent(new BatchInsertionEvent(this,dicDistrictList));
                    dicDistrictList = new ArrayList<>();
                }

                cityAddressCodeParent = provinceAdCode;
                JSONArray cityDistrictses = provinceObject.getJSONArray("districts");
                if (cityDistrictses.size() > 0){
                    for (int city = 0;city < cityDistrictses.size();city++){
                        //解析地级市
                        cityObject = (JSONObject) cityDistrictses.get(city);
                        cityAdCode = (String)cityObject.get("adcode");
                        cityName = (String)cityObject.get("name");
                        cityLevelName = (String)cityObject.get("level");
                        cityLevel = DIC_DISTRICT_MAP.get(cityLevelName);
                        //插入地级市节点
                        DicDistrict cityDicDistrict = new DicDistrict();
                        cityDicDistrict.setAddressCode(cityAdCode);
                        cityDicDistrict.setAddressName(cityName);
                        cityDicDistrict.setParentAddressCode(cityAddressCodeParent);
                        cityDicDistrict.setLevel(cityLevel);
//                        dicDistrictMapper.insert(cityDicDistrict);
                        dicDistrictList.add(cityDicDistrict);
                        if (dicDistrictList.size() == SAVEBATCH_DICDISTRICT){
                            applicationContext.publishEvent(new BatchInsertionEvent(this,dicDistrictList));
                            dicDistrictList = new ArrayList<>();
                        }

                        districtAddressCodeParent = cityAdCode;
                        JSONArray districts = (JSONArray)cityObject.getJSONArray("districts");
                        if (districts.size() > 0){
                            for (int d = 0;d < districts.size(); d++){
                                district = (JSONObject)districts.get(d);
                                districtAdCode = (String)district.get("adcode");
                                districtName = (String)district.get("name");
                                districtLevelName = (String)district.get("level");
                                districtLevel = DIC_DISTRICT_MAP.get(districtLevelName);
                                //插入地级市节点
                                DicDistrict districtDicDistrict = new DicDistrict();
                                districtDicDistrict.setAddressCode(districtAdCode);
                                districtDicDistrict.setAddressName(districtName);
                                districtDicDistrict.setParentAddressCode(districtAddressCodeParent);
                                districtDicDistrict.setLevel(districtLevel);
//                                dicDistrictMapper.insert(districtDicDistrict);
                                dicDistrictList.add(districtDicDistrict);
                                if (dicDistrictList.size() == SAVEBATCH_DICDISTRICT){
                                    applicationContext.publishEvent(new BatchInsertionEvent(this,dicDistrictList));
                                    dicDistrictList = new ArrayList<>();
                                }
                            }
                        }
                    }
                }
            }
        }

        //3.插入数据库,在过程2中完成了
        if (dicDistrictList.size() > 0){
            applicationContext.publishEvent(new BatchInsertionEvent(this,dicDistrictList));
            dicDistrictList = new ArrayList<>();
        }

        return ResponseResult.success();
    }
}